package com.gsq.learning.mybatisplugin.plugin.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

/**
 * 统计sql执行时间
 */
@Intercepts(
        @Signature(
                type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class, Integer.class}
        )
)
public class MyStatementInterceptor implements Interceptor {

    private long time;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        StatementHandler target = (StatementHandler) invocation.getTarget();
        System.out.println("======> MyStatementInterceptor：" + target);

        BoundSql boundSql = target.getBoundSql();
        String sql = boundSql.getSql();
        long startTime = System.currentTimeMillis();

        Object ret = invocation.proceed();

        long endTime = System.currentTimeMillis();
        System.out.println("======> sql：" + sql);
        if (endTime - startTime > time) {
            System.out.println("======> 本此执行超时：" + (endTime -  startTime));
        } else {
            System.out.println("======> 本此执行时间：" + (endTime -  startTime));
        }

        return ret;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties arg0) {
        System.out.println("======> env value: " + arg0.getProperty("time"));
        time = Long.parseLong(arg0.getProperty("time"));
    }
}
